package product;

import java.awt.Color;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.PlainDocument;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;

import java.awt.Font;
import javax.swing.border.LineBorder;
import java.awt.Dimension;
import java.awt.SystemColor;

public class CompanyInput extends JInternalFrame {
	// HashMap<String, CompanyData> map; // CompanyInput에 선언한 HashMap을 쓰기위한
	// 소스부분!
	// 필드 부분
	ProductMain4 pm;
	String fileName = "noname"; // 이미지의 로컬 경로 저장
	Image img; // 로고 이미지 저장
	String folder = "img\\logo\\"; // 이미지를 저장할 경로 폴더
	File f;
	boolean Flag = true;
	
	// ----------------------------------------------------------------------------------//
	private JPanel contentPane;
	private JTextField txtName;
	private JTextField txtAddress;
	private JTextField txtCeo;
	private JButton btn_input;
	private JTextField txtP1;
	private JLabel lblNewLabel_4;
	private JTextField txtP2;
	private JLabel label_1;
	private JTextField txtP3;
	private JTextField txtF1;
	private JLabel label_2;
	private JTextField txtF2;
	private JLabel label_3;
	private JTextField txtF3;
	private JLabel Logoimg;
	private JComboBox comboBox;
	private JButton btn_img;
	private JButton btn_dup;
	private JFormattedTextField txtCode;
	private JPanel panel;
	private JLabel lblLicenseNumber;
	private JLabel lblCompanyName;
	private JLabel label_5;
	private JLabel lblCompanyAddress;
	private JLabel lblPhoneNumber;
	private JLabel lblFaxNumber;
	private JPanel panel_1;
	private JPanel panel_2;
	private JPanel panel_3;
	private JLabel lblCustomerInput;
	private JLabel label_9;
	private JPanel panel_4;
	private JPanel panel_5;

	// 회사로고의 이미지를 부르는 logo()메서드!
	public void logo() {
		try {
			JFileChooser fc = new JFileChooser();
			int yn = fc.showOpenDialog(this);
			if (yn == JFileChooser.APPROVE_OPTION) {
				File f = fc.getSelectedFile();
				fileName = f.getPath();
				System.out.println(fileName);
				// 불러들인 파일 이미지를 label에 바로 뿌려준다.
				Logoimg.setIcon(new ImageIcon(fileName));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public CompanyInput(ProductMain4 pm) {
		super("CustomerInput", true, true, true, false);
		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameActivated(InternalFrameEvent e) {
				txtCode.setText("");
				txtCode.requestFocus();
			}
		});
		setTitle("Customer Input");
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 546, 452);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getPanel());
		contentPane.add(getBtn_input());
		contentPane.add(getPanel_3());
		contentPane.add(getLabel_9());

		this.pm = pm;
	}

	public void setinput() {
		String sql = "insert into customer(num, name, ceo, address, phone, fax) values(?,?,?,?,?,?)";
		String p = txtP1.getText() + "-" + txtP2.getText() + "-" + txtP3.getText();
		String f = txtF1.getText() + "-" + txtF2.getText() + "-" + txtF3.getText();
		
		try {
			PreparedStatement pstmt = pm.conn.prepareStatement(sql);
			pstmt.setString(1, txtCode.getText());
			pstmt.setString(2, txtName.getText());
			pstmt.setString(3, txtCeo.getText());
			pstmt.setString(4, txtAddress.getText());
			pstmt.setString(5, p);
			pstmt.setString(6, f);

			pstmt.executeUpdate();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	private JTextField getTxtName() {
		if (txtName == null) {
			txtName = new JTextField();
			txtName.setBounds(172, 64, 189, 30);
			txtName.setColumns(10);
		}
		return txtName;
	}

	private JTextField getTxtAddress() {
		if (txtAddress == null) {
			txtAddress = new JTextField();
			txtAddress.setBounds(172, 148, 316, 30);
			txtAddress.setColumns(10);
		}
		return txtAddress;
	}

	private JTextField getTxtCeo() {
		if (txtCeo == null) {
			txtCeo = new JTextField();
			txtCeo.setBounds(172, 106, 189, 30);
			txtCeo.setColumns(10);
		}
		return txtCeo;
	}

	private JButton getBtn_input() {
		if (btn_input == null) {
			btn_input = new JButton("Save");
			btn_input.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// ---------------------입력 부분의 소스이며 예외처리 부분입니다.---------------------//
					String p = txtP1.getText() + "-" + txtP2.getText() + "-" + txtP3.getText();
					String f = txtF1.getText() + "-" + txtF2.getText() + "-" + txtF3.getText();
	System.out.println("가");
					try {
						if (txtCode.getText().equals("")
								|| txtName.getText().equals("")
								|| txtAddress.getText().equals("")
								|| txtCeo.getText().equals("")) {
							JOptionPane.showMessageDialog(null,	"회사 정보를 입력해 주세요.");
							txtCode.setText("");
							txtName.setText("");
							txtAddress.setText("");
							txtP1.setText("");
							txtP2.setText("");
							txtP3.setText("");
							txtF1.setText("");
							txtF2.setText("");
							txtF3.setText("");
							txtCeo.setText("");
							txtCode.requestFocus();
							return;
						}

						Integer.parseInt(txtP1.getText());

						Integer.parseInt(txtP2.getText());

						Integer.parseInt(txtP3.getText());

						Integer.parseInt(txtF1.getText());

						Integer.parseInt(txtF2.getText());

						Integer.parseInt(txtF3.getText());

					} catch (NumberFormatException e2) {
						JOptionPane.showMessageDialog(null,	"전화번호/팩스에 숫자만 입력해 주세요.");
						txtP1.setText("");
						txtP2.setText("");
						txtP3.setText("");
						txtF1.setText("");
						txtF2.setText("");
						txtF3.setText("");
						txtP1.requestFocus();
						return;
					}
					// -------------------------------------------------------------------------------//

					// 회사정보의 데이터를 ComapanyData에 의해 저장하기 위한 소스부분!

					if (!txtCode.getText().equals("") && !txtName.getText().equals("") 
						&& !txtAddress.getText().equals("")
						&& !txtCeo.getText().equals("")) {
		System.out.println("나");
						setinput();
						JOptionPane.showMessageDialog(null, "입력이 되었습니다.");
						

						// 회원정보가 저장이 되면서 이미지는 지정된 폴더에 이미지가 저장!
						try {
							// 이부분은 이미지가 지정된 폴더에 저장하기 위해 폴더가 없을경우 폴더를 생성하는 부분!
//							File f1 = new File(folder);
//							if (!f1.exists()) {
//								f1.mkdirs();
//							}
							// 폴더에 저장하기 위해 선택한 이미지를 Key값으로 지정하여 저장하는 부분
							// [이미지확장자(.png)]
System.out.println("다");
							BufferedImage img = ImageIO.read(new File(fileName));
							ImageIO.write(img, "png", new File(folder + txtCode.getText() + ".png"));
						} catch (Exception ex) {
							ex.printStackTrace();
						}
						if(pm.tList != null){
							pm.tList.searchData();
						}
					}
					txtCode.setText("");
					txtName.setText("");
					txtAddress.setText("");
					txtP1.setText("");
					txtP2.setText("");
					txtP3.setText("");
					txtF1.setText("");
					txtF2.setText("");
					txtF3.setText("");
					txtCeo.setText("");
					Logoimg.setIcon(new ImageIcon(""));
					txtCode.requestFocus();
				}
			});
			btn_input.setBounds(418, 385, 102, 30);
		}
		return btn_input;
	}
	private JTextField getTxtP1() {
		if (txtP1 == null) {
			txtP1 = new JTextField();
			txtP1.setBorder(null);
			txtP1.setBounds(8, 1, 50, 28);
			txtP1.addKeyListener(new KeyAdapter() {

				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtP1.getText();
					int len = str.length();
					if (len == 3) {
						txtP2.requestFocus();
					}
				}
			});
			txtP1.setDocument(new JTextFieldLimit(3));
		}
		return txtP1;
	}

	private JLabel getLblNewLabel_4() {
		if (lblNewLabel_4 == null) {
			lblNewLabel_4 = new JLabel("-");
			lblNewLabel_4.setFont(new Font("굴림", Font.BOLD, 20));
			lblNewLabel_4.setBounds(60, 0, 19, 30);
		}
		return lblNewLabel_4;
	}

	private JTextField getTxtP2() {
		if (txtP2 == null) {
			txtP2 = new JTextField();
			txtP2.setBorder(null);
			txtP2.setBounds(87, 1, 90, 28);
			txtP2.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtP2.getText();
					int len = str.length();
					if (len == 4) {
						txtP3.requestFocus();
					}
				}
			});
			txtP2.setDocument(new JTextFieldLimit(4));

		}
		return txtP2;
	}

	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("-");
			label_1.setFont(new Font("굴림", Font.BOLD, 20));
			label_1.setBounds(181, 0, 18, 30);
		}
		return label_1;
	}

	private JTextField getTxtP3() {
		if (txtP3 == null) {
			txtP3 = new JTextField();
			txtP3.setBorder(null);
			txtP3.setBounds(211, 1, 76, 28);
			txtP3.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtP3.getText();
					int len = str.length();
					if (len == 4) {
						txtF1.requestFocus();
					}
				}
			});
			txtP3.setDocument(new JTextFieldLimit(4));
		}
		return txtP3;
	}

	private JTextField getTextField_3() {
		if (txtF1 == null) {
			txtF1 = new JTextField();
			txtF1.setBorder(null);
			txtF1.setBounds(8, 1, 50, 28);
			txtF1.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtF1.getText();
					int len = str.length();
					if (len == 3) {
						txtF2.requestFocus();
					}
				}
			});
			txtF1.setDocument(new JTextFieldLimit(3));
		}
		return txtF1;
	}

	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("-");
			label_2.setFont(new Font("굴림", Font.BOLD, 20));
			label_2.setBounds(60, 0, 17, 30);
		}
		return label_2;
	}

	private JTextField getTextField_1_1() {
		if (txtF2 == null) {
			txtF2 = new JTextField();
			txtF2.setBorder(null);
			txtF2.setBounds(87, 1, 87, 28);
			txtF2.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtF2.getText();
					int len = str.length();
					if (len == 4) {
						txtF3.requestFocus();
					}
				}
			});
			txtF2.setDocument(new JTextFieldLimit(4));
		}
		return txtF2;
	}

	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("-");
			label_3.setFont(new Font("굴림", Font.BOLD, 20));
			label_3.setBounds(181, 0, 20, 30);
		}
		return label_3;
	}

	private JTextField getTextField_2_1() {
		if (txtF3 == null) {
			txtF3 = new JTextField();
			txtF3.setBorder(null);
			txtF3.setBounds(211, 1, 76, 28);
			txtF3.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					String str = txtF3.getText();
					int len = str.length();
					if (len == 4) {
						txtCeo.requestFocus();
					}
				}
			});
			txtF3.setDocument(new JTextFieldLimit(4));
		}
		return txtF3;
	}

	private JLabel getLogoimg() {
		if (Logoimg == null) {
			Logoimg = new JLabel("");
			Logoimg.setBounds(389, 10, 100, 100);
			Logoimg.setBorder(new LineBorder(Color.GRAY, 2));
			Logoimg.setForeground(UIManager.getColor("Button.focus"));
		}
		return Logoimg;
	}

	// 텍스트필드 문자열 제한 수 소스!!
	class JTextFieldLimit extends PlainDocument {
		private int limit;

		JTextFieldLimit(int limit) {
			super();
			this.limit = limit;
		}

		JTextFieldLimit(int limit, boolean upper) {
			super();
			this.limit = limit;
		}

		public void insertString(int offset, String str, AttributeSet attr)
				throws BadLocationException {
			if (str == null)
				return;

			if ((getLength() + str.length()) <= limit) {
				super.insertString(offset, str, attr);
			}
		}
	}

	// ------------------------------------------------------------------------------------------------------//

	private JButton getBtn_img() {
		if (btn_img == null) {
			btn_img = new JButton("+ Image");
			btn_img.setBounds(389, 111, 100, 26);
			btn_img.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					logo();
				}
			});
		}
		return btn_img;
	}
	
	private JButton getBtn_dup() {
		if (btn_dup == null) {
			btn_dup = new JButton("Check");
			btn_dup.setBounds(270, 7, 73, 30);
			btn_dup.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					String code = txtCode.getText();
					String sql = "select num from customer";
					
					try{
						PreparedStatement pstmt = pm.conn.prepareStatement(sql);
						ResultSet rs = pstmt.executeQuery();
						
						boolean flag = false;
						while(rs.next()){
							if(txtCode.getText().equals(rs.getString(1))){
								JOptionPane.showMessageDialog(null, "중복된 코드가 있습니다.");
								txtCode.setText("");
								txtCode.requestFocus();
								flag = true;
								break;
							}
						}
						if(!flag){
							JOptionPane.showMessageDialog(null, "중복된 코드가 없습니다.");
						}
							
					}catch(Exception ex){
						ex.printStackTrace();
						System.out.println("중복검사 에러");
					}
				}
			});
		}
		return btn_dup;
	}
	private JFormattedTextField getTxtCode() {
		if (txtCode == null) {
			txtCode = new JFormattedTextField();
			txtCode.setBounds(158, 8, 103, 30);
			try {
				txtCode.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("###-##-#####")));
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return txtCode;
	}
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setBorder(new LineBorder(Color.GRAY, 2));
			panel.setBackground(SystemColor.inactiveCaptionBorder);
			panel.setBounds(12, 102, 506, 276);
			panel.setLayout(null);
			panel.add(getTxtName());
			panel.add(getTxtCeo());
			panel.add(getTxtAddress());
			panel.add(getLabel_4_1());
			panel.add(getLabel_5());
			panel.add(getLblCompanyAddress());
			panel.add(getLblPhoneNumber());
			panel.add(getLblFaxNumber());
			panel.add(getPanel_1());
			panel.add(getPanel_2());
			panel.add(getLogoimg());
			panel.add(getBtn_img());
			panel.add(getPanel_4());
			panel.add(getPanel_5());
		}
		return panel;
	}
	private JLabel getLabel_4() {
		if (lblLicenseNumber == null) {
			lblLicenseNumber = new JLabel("License Number ");
			lblLicenseNumber.setBounds(8, 6, 143, 30);
			lblLicenseNumber.setPreferredSize(new Dimension(70, 20));
			lblLicenseNumber.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
		}
		return lblLicenseNumber;
	}
	private JLabel getLabel_4_1() {
		if (lblCompanyName == null) {
			lblCompanyName = new JLabel("Company Name");
			lblCompanyName.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
			lblCompanyName.setBounds(21, 64, 170, 30);
		}
		return lblCompanyName;
	}
	private JLabel getLabel_5() {
		if (label_5 == null) {
			label_5 = new JLabel("ChairMan");
			label_5.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
			label_5.setBounds(21, 106, 170, 30);
		}
		return label_5;
	}
	private JLabel getLblCompanyAddress() {
		if (lblCompanyAddress == null) {
			lblCompanyAddress = new JLabel("Company Address");
			lblCompanyAddress.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
			lblCompanyAddress.setBounds(21, 147, 149, 30);
		}
		return lblCompanyAddress;
	}
	private JLabel getLblPhoneNumber() {
		if (lblPhoneNumber == null) {
			lblPhoneNumber = new JLabel("Phone Number");
			lblPhoneNumber.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
			lblPhoneNumber.setBounds(21, 190, 170, 30);
		}
		return lblPhoneNumber;
	}
	private JLabel getLblFaxNumber() {
		if (lblFaxNumber == null) {
			lblFaxNumber = new JLabel("Fax Number");
			lblFaxNumber.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));
			lblFaxNumber.setBounds(21, 232, 170, 30);
		}
		return lblFaxNumber;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setBorder(new LineBorder(Color.GRAY));
			panel_1.setBackground(SystemColor.controlLtHighlight);
			panel_1.setBounds(173, 232, 315, 30);
			panel_1.setLayout(null);
			panel_1.add(getTextField_3());
			panel_1.add(getLabel_2());
			panel_1.add(getTextField_1_1());
			panel_1.add(getLabel_3());
			panel_1.add(getTextField_2_1());
		}
		return panel_1;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setBorder(new LineBorder(Color.GRAY));
			panel_2.setBackground(SystemColor.text);
			panel_2.setBounds(173, 190, 315, 30);
			panel_2.setLayout(null);
			panel_2.add(getTxtP1());
			panel_2.add(getTxtP2());
			panel_2.add(getLblNewLabel_4());
			panel_2.add(getLabel_1());
			panel_2.add(getTxtP3());
		}
		return panel_2;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(null);
			panel_3.setBorder(new LineBorder(Color.GRAY, 2));
			panel_3.setBounds(-11, -11, 568, 61);
			panel_3.add(getLblCustomerInput());
		}
		return panel_3;
	}
	private JLabel getLblCustomerInput() {
		if (lblCustomerInput == null) {
			lblCustomerInput = new JLabel("Customer Input");
			lblCustomerInput.setHorizontalAlignment(SwingConstants.CENTER);
			lblCustomerInput.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 25));
			lblCustomerInput.setBounds(9, 10, 546, 46);
		}
		return lblCustomerInput;
	}
	private JLabel getLabel_9() {
		if (label_9 == null) {
			label_9 = new JLabel("Customer Information");
			label_9.setForeground(Color.DARK_GRAY);
			label_9.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 20));
			label_9.setBounds(13, 65, 224, 30);
		}
		return label_9;
	}
	private JPanel getPanel_4() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setBackground(Color.LIGHT_GRAY);
			panel_4.setBounds(375, 9, 2, 130);
		}
		return panel_4;
	}
	private JPanel getPanel_5() {
		if (panel_5 == null) {
			panel_5 = new JPanel();
			panel_5.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
			panel_5.setBackground(Color.WHITE);
			panel_5.setBounds(14, 10, 349, 46);
			panel_5.setLayout(null);
			panel_5.add(getLabel_4());
			panel_5.add(getTxtCode());
			panel_5.add(getBtn_dup());
		}
		return panel_5;
	}
}
